// pages/products/detail.js
import { requireLogin, checkLogin } from '../../utils/auth'
import { createAndPayOrder } from '../../utils/order'
import { 
  showToast, 
  showLoading, 
  hideLoading, 
  showProductConfirm,
  chooseAddress,
  chooseDeliveryType,
  DELIVERY_TYPE
} from '../../utils/tips'

const app = getApp()

Page({
  data: {
    id: '',
    product: null,
    currentImage: 0,
    quantity: 1,
    isFavorite: false,
    showSpecPicker: false,
    selectedSpec: null,
    specs: [],
    selectedSpecs: {},
    currentStock: 0,
    currentPrice: 0,
    remark: '',
  },

  onLoad(options) {
    if (options.id) {
      this.setData({ id: options.id })
      this.loadProduct(options.id)
      this.checkFavorite(options.id)
    }
  },

  // 加载商品信息
  async loadProduct(id) {
    try {
      const db = wx.cloud.database()
      const { data: product } = await db.collection('products').doc(id).get()
      
      // 确保商品数据中包含 shopId
      if (!product.shopId) {
        console.error('商品数据缺少店铺ID')
        return
      }

      // 加载店铺信息
      const { data: shop } = await db.collection('shops').doc(product.shopId).get()
      
      // 合并商品和店铺信息
      product.shop = {
        id: shop._id,
        name: shop.name,
        logo: shop.logo,
        cover: shop.cover,
        address: shop.address,
        phone: shop.phone,
        businessHours: shop.businessHours,
        monthlySales: shop.monthlySales,
        rating: shop.rating,
        status: shop.status,
        description: shop.description
      }
      
      // 设置规格数据
      const specs = []
      if (product.specs && Array.isArray(product.specs)) {
        specs.push(...product.specs)
      }

      // 获取默认规格组合（选择库存最多的组合）
      let defaultCombo = null
      let defaultSpecs = {}
      if (product.specCombos && product.specCombos.length > 0) {
        // 找出库存最多的规格组合
        defaultCombo = product.specCombos.reduce((max, current) => 
          current.stock > max.stock ? current : max
        , product.specCombos[0])

        // 设置默认选中的规格
        defaultSpecs = { ...defaultCombo.specs }
      }
      
      this.setData({ 
        product,
        specs,
        selectedSpecs: defaultSpecs,
        selectedSpec: Object.entries(defaultSpecs)
          .map(([key, value]) => `${key}:${value}`)
          .join('、'),
        currentStock: defaultCombo ? defaultCombo.stock : 0,
        currentPrice: defaultCombo ? defaultCombo.price : 0
      })
    } catch (error) {
      console.error('加载商品信息失败：', error)
      showToast('加载失败')
    }
  },

  // 检查是否已收藏
  async checkFavorite(productId) {
    if (!app.globalData.openid) {
      return
    }

    try {
      const db = wx.cloud.database()
      const { data } = await db.collection('favorites')
        .where({
          userId: app.globalData.openid,
          'product.id': productId
        })
        .get()
      
      this.setData({ isFavorite: data.length > 0 })
    } catch (error) {
      console.error('检查收藏状态失败：', error)
    }
  },

  // 轮播图切换
  onImageChange(e) {
    this.setData({
      currentImage: e.detail.current
    })
  },

  // 调整数量
  adjustQuantity(e) {
    const { type } = e.currentTarget.dataset
    let { quantity, currentStock } = this.data

    if (type === 'minus' && quantity > 1) {
      quantity--
    } else if (type === 'plus' && quantity < currentStock) {
      quantity++
    } else if (type === 'plus' && quantity >= currentStock) {
      showToast(`当前规格库存不足，剩余${currentStock}件`, 'none')
      return
    }

    this.setData({ quantity })
  },

  // 收藏/取消收藏
  async toggleFavorite() {
    if (!checkLogin()) return

    const { id, product, isFavorite, currentPrice } = this.data

    try {
      const db = wx.cloud.database()
      
      if (isFavorite) {
        // 取消收藏
        const { data } = await db.collection('favorites')
          .where({
            userId: app.globalData.openid,
            'product.id': id
          })
          .get()
        
        if (data.length > 0) {
          await db.collection('favorites').doc(data[0]._id).remove()
        }
        
        showToast('已取消收藏')
      } else {
        // 添加收藏
        await db.collection('favorites').add({
          data: {
            userId: app.globalData.openid,
            product: {
              id: product._id,
              name: product.name,
              price: currentPrice,  // 使用当前规格价格
              image: product.images[0],
              specCombos: product.specCombos,  // 保存规格组合信息
              selectedSpecs: this.data.selectedSpecs  // 保存已选规格
            },
            createTime: db.serverDate()
          }
        })
        
        showToast('已收藏')
      }
      
      this.setData({ isFavorite: !isFavorite })
    } catch (error) {
      console.error('收藏操作失败：', error)
      showToast('操作失败', 'none')
    }
  },

  // 检查商品是否可购买
  checkProductAvailable() {
    if (!checkLogin()) {
      return {
        success: false,
        message: '请先登录',
        type: 'none'
      }
    }

    const { product, selectedSpecs, quantity } = this.data
    
    // 检查是否有规格选项
    if (this.data.specs.length > 0) {
      // 检查是否选择了完整规格
      const allSpecsSelected = Object.keys(selectedSpecs).length === this.data.specs.length
      if (!allSpecsSelected) {
        return {
          success: false,
          message: '请选择商品规格',
          type: 'none'
        }
      }

      // 检查选择的规格组合是否存在
      const matchedCombo = product.specCombos.find(combo => 
        Object.entries(combo.specs).every(([key, value]) => 
          selectedSpecs[key] === value
        )
      )

      if (!matchedCombo) {
        return {
          success: false,
          message: '所选规格组合不存在',
          type: 'none'
        }
      }

      // 检查库存
      if (quantity > matchedCombo.stock) {
        return {
          success: false,
          message: `当前规格库存不足，剩余${matchedCombo.stock}件`,
          type: 'none'
        }
      }
    }

    return {
      success: true,
      message: '操作成功',
      type: 'success'
    }
  },

  // 加入购物车
  async addToCart() {
    const checkResult = this.checkProductAvailable()
    if (!checkResult.success) {
      showToast(checkResult.message, checkResult.type)
      return
    }

    const { product, quantity, selectedSpecs, remark, currentPrice } = this.data

    // 显示确认提示
    const confirmResult = await showProductConfirm(
      product,
      quantity,
      selectedSpecs,
      remark,
      '加入购物车'
    )
    
    if (!confirmResult.confirm) return

    try {
      showLoading('正在加入购物车...')
      
      const db = wx.cloud.database()
      
      // 新增购物车项
      await db.collection('cart').add({
        data: {
          userId: app.globalData.openid,
          shopId: product.shopId,
          shop: product.shop,
          products: [{
            id: product._id,
            name: product.name,
            price: currentPrice,  // 使用当前规格的价格
            quantity,
            image: product.images[0],
            specs: selectedSpecs,
            remark: remark || ''
          }],
          createTime: db.serverDate(),
          updateTime: db.serverDate()
        }
      })
      
      showToast('已加入购物车', 'success')
    } catch (error) {
      console.error('加入购物车失败：', error)
      showToast('加入购物车失败')
    } finally {
      hideLoading()
    }
  },

  // 生成订单号
  generateOrderNo() {
    const now = new Date();
    const year = now.getFullYear().toString().slice(2);
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    const day = now.getDate().toString().padStart(2, '0');
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    const seconds = now.getSeconds().toString().padStart(2, '0');
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
    
    return `ON${year}${month}${day}${hours}${minutes}${seconds}${random}`;
  },

  // 格式化时间
  formatDate(date) {
    const d = new Date(date);
    const year = d.getFullYear();
    const month = (d.getMonth() + 1).toString().padStart(2, '0');
    const day = d.getDate().toString().padStart(2, '0');
    const hour = d.getHours().toString().padStart(2, '0');
    const minute = d.getMinutes().toString().padStart(2, '0');
    const second = d.getSeconds().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
  },

  // 立即购买
  async buyNow() {
    const checkResult = this.checkProductAvailable()
    if (!checkResult.success) {
      showToast(checkResult.message, checkResult.type)
      return
    }

    const { product, quantity, selectedSpecs, remark, currentPrice } = this.data

    try {
      // 显示确认提示
      const confirmResult = await showProductConfirm(
        product,
        quantity,
        selectedSpecs,
        remark,
        '购买'
      )
      
      if (!confirmResult.confirm) return

      // 选择配送方式
      const deliveryType = await chooseDeliveryType()
      
      let address = null
      if (deliveryType.value === DELIVERY_TYPE.DELIVERY.value) {
        // 需要配送时才选择地址
        // 选择收货地址前先检查权限
        const setting = await wx.getSetting()
        if (!setting.authSetting['scope.address']) {
          await wx.authorize({
            scope: 'scope.address'
          })
        }

        // 选择收货地址
        showLoading('正在选择地址...')
        address = await chooseAddress()
        hideLoading()
        
        if (!address) {
          throw new Error('请选择收货地址')
        }
      }

      // 创建订单数据
      const orderData = {
        shopId: product.shopId,
        shop: product.shop,
        products: [{
          id: product._id,
          name: product.name,
          price: currentPrice,  // 使用当前规格的价格
          quantity,
          image: product.images[0],
          specs: selectedSpecs,
          remark: remark || ''
        }],
        totalAmount: currentPrice * quantity,  // 使用当前规格的价格计算总价
        remark: remark || '',
        deliveryType: deliveryType.value,
        deliveryTypeDesc: deliveryType.desc
      }

      // 如果需要配送，添加地址信息
      if (address) {
        orderData.address = {
          name: address.name,
          phone: address.phone,
          province: address.province,
          city: address.city,
          district: address.district,
          detail: address.detail
        }
      }

      const { orderId } = await createAndPayOrder(orderData)

      // 跳转到订单详情页
      wx.redirectTo({
        url: `/pages/order/detail?id=${orderId}`,
        fail: (error) => {
          console.error('跳转失败：', error)
          showToast('跳转订单页面失败')
        }
      })

    } catch (error) {
      hideLoading()
      console.error('创建订单失败：', error)
      showToast(error.message || '创建订单失败')
    }
  },

  // 显示规格选择器
  showSpecPicker() {
    this.setData({ showSpecPicker: true });
  },

  // 隐藏规格选择器
  hideSpecPicker() {
    this.setData({ showSpecPicker: false });
  },

  // 选择规格
  selectSpec(e) {
    const { group, value } = e.currentTarget.dataset
    let selectedSpecs = { ...this.data.selectedSpecs }
    selectedSpecs[group] = value
    
    this.setData({ 
      selectedSpecs,
      selectedSpec: Object.entries(selectedSpecs)
        .map(([key, value]) => `${key}:${value}`)
        .join('、')
    })

    // 更新价格和库存
    this.updatePriceAndStock(selectedSpecs)
  },

  // 更新价格和库存
  updatePriceAndStock(selectedSpecs) {
    const { product } = this.data
    const allSpecsSelected = Object.keys(selectedSpecs).length === this.data.specs.length

    if (allSpecsSelected && product.specCombos) {
      // 查找匹配的规格组合
      const matchedCombo = product.specCombos.find(combo => {
        return Object.entries(combo.specs).every(([key, value]) => 
          selectedSpecs[key] === value
        )
      })

      if (matchedCombo) {
        // 如果当前选择的数量超过库存，调整数量并提示
        if (this.data.quantity > matchedCombo.stock) {
          showToast(`当前规格库存不足，已自动调整数量`, 'none')
        }

        this.setData({
          currentStock: matchedCombo.stock,
          currentPrice: matchedCombo.price,
          quantity: Math.min(this.data.quantity, matchedCombo.stock)
        })
      } else {
        showToast('所选规格组合不存在', 'none')
        // 重置为默认规格（库存最多的组合）
        const defaultCombo = product.specCombos.reduce((max, current) => 
          current.stock > max.stock ? current : max
        , product.specCombos[0])

        this.setData({
          currentStock: defaultCombo.stock,
          currentPrice: defaultCombo.price,
          quantity: Math.min(this.data.quantity, defaultCombo.stock),
          selectedSpecs: { ...defaultCombo.specs },
          selectedSpec: Object.entries(defaultCombo.specs)
            .map(([key, value]) => `${key}:${value}`)
            .join('、')
        })
      }
    }
  },

  // 确认规格选择
  confirmSpec() {
    const allSpecsSelected = Object.keys(this.data.selectedSpecs).length === this.data.specs.length;
    if (!allSpecsSelected) {
      wx.showToast({
        title: '请选择完整规格',
        icon: 'none'
      });
      return;
    }
    this.hideSpecPicker();
  },

  // 跳转到店铺
  goToShop() {
    const { shop } = this.data.product
    if (!shop || !shop.id) {
      showToast('店铺信息不存在')
      return
    }
    
    wx.navigateTo({
      url: `/pages/shops/detail?id=${shop.id}`
    })
  },

  // 备注输入处理
  onRemarkInput(e) {
    this.setData({
      remark: e.detail.value
    });
  },
})